/*
 * @Author: TT-hzy 
 * @Date: 2024-05-23 11:13:47
 * @LastEditors: TT-hzy 
 * @LastEditTime: 2024-05-23 11:13:48
 * @Description: 
 */
import 'dart:convert';

import 'dart:async';

import 'package:hzy_normal_tool/hzy_normal_tool.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesTool {
  static SharedPreferencesTool? _singleton;
  static SharedPreferences? _store;

  static Future<SharedPreferencesTool?> getInstance() async {
    if (_singleton == null) {
      if (_singleton == null) {
        var singleton = SharedPreferencesTool._();
        await singleton._init();
        _singleton = singleton;
      }
    }
    return _singleton;
  }

  SharedPreferencesTool._();

  Future _init() async {
    _store = await SharedPreferences.getInstance();
    if (_store == null) {
      debugLog("本地存储库,初始化失败");
    } else {
      debugLog("本地存储库,初始化完成");
    }
  }

  /// put object.
  static Future<bool>? putObject(String key, Object value) {
    return _store?.setString(key, json.encode(value));
  }

  /// get obj.
  static T? getObj<T>(String key, T Function(Map v) f, {T? defValue}) {
    Map? map = getObject(key);
    return map == null ? defValue : f(map);
  }

  /// get object.
  static Map? getObject(String key) {
    String? data = _store?.getString(key);
    return (data == null || data.isEmpty) ? null : json.decode(data);
  }

  /// put object list.
  static Future<bool>? putObjectList(String key, List<Object> list) {
    List<String>? dataList = list.map((value) {
      return json.encode(value);
    }).toList();
    return _store?.setStringList(key, dataList);
  }

  /// get obj list.
  static List<T>? getObjList<T>(String key, T Function(Map v) f,
      {List<T>? defValue = const []}) {
    List<Map>? dataList = getObjectList(key);
    List<T>? list = dataList?.map((value) {
      return f(value);
    }).toList();
    return list ?? defValue;
  }

  /// get object list.
  static List<Map>? getObjectList(String key) {
    List<String>? dataLis = _store?.getStringList(key);
    return dataLis?.map((value) {
      Map dataMap = json.decode(value);
      return dataMap;
    }).toList();
  }

  /// get string.
  static String? getString(String key, {String? defValue = ''}) {
    return _store?.getString(key) ?? defValue;
  }

  /// put string.
  static Future<bool>? putString(String key, String value) {
    return _store?.setString(key, value);
  }

  /// get bool.
  static bool? getBool(String key, {bool? defValue = false}) {
    return _store?.getBool(key) ?? defValue;
  }

  /// put bool.
  static Future<bool>? putBool(String key, bool value) {
    return _store?.setBool(key, value);
  }

  /// get int.
  static int? getInt(String key, {int? defValue = 0}) {
    return _store?.getInt(key) ?? defValue;
  }

  /// put int.
  static Future<bool>? putInt(String key, int value) {
    return _store?.setInt(key, value);
  }

  /// get double.
  static double? getDouble(String key, {double? defValue = 0.0}) {
    return _store?.getDouble(key) ?? defValue;
  }

  /// put double.
  static Future<bool>? putDouble(String key, double value) {
    return _store?.setDouble(key, value);
  }

  /// get string list.
  static List<String>? getStringList(String key,
      {List<String>? defValue = const []}) {
    return _store?.getStringList(key) ?? defValue;
  }

  /// put string list.
  static Future<bool>? putStringList(String key, List<String> value) {
    return _store?.setStringList(key, value);
  }

  /// get dynamic.
  static dynamic getDynamic(String key, {Object? defValue}) {
    return _store?.get(key) ?? defValue;
  }

  /// have key.
  static bool? haveKey(String key) {
    return _store?.getKeys().contains(key);
  }

  /// contains Key.
  static bool? containsKey(String key) {
    return _store?.containsKey(key);
  }

  /// get keys.
  static Set<String>? getKeys() {
    return _store?.getKeys();
  }

  /// remove.
  static Future<bool>? remove(String key) {
    return _store?.remove(key);
  }

  /// clear.
  static Future<bool>? clear() {
    return _store?.clear();
  }

  /// Fetches the latest values from the host platform.
  static Future<void>? reload() {
    return _store?.reload();
  }

  ///Sp is initialized.
  static bool isInitialized() {
    return _store != null;
  }

  /// get Sp.
  static SharedPreferences? getSp() {
    return _store;
  }

  // ========== 用户登录相关方法 ========== //

  /// 保存登录信息
  /// [username] 用户名
  /// [userId] 用户ID
  /// [token] 登录令牌
  /// [password] 密码（可选，仅在记住密码时保存）
  /// [rememberPassword] 是否记住密码
  static Future<bool> saveLoginInfo({
    required String username,
    required String userId,
    required String token,
    String? password,
    bool rememberPassword = false,
  }) async {
    try {
      await putBool('is_logged_in', true);
      await putString('current_username', username);
      await putString('current_user_id', userId);
      await putString('current_token', token);
      await putBool('remember_password', rememberPassword);
      
      if (rememberPassword && password != null) {
        await putString('saved_password', password);
      } else {
        await remove('saved_password');
      }
      
      return true;
    } catch (e) {
      debugLog('保存登录信息失败: $e');
      return false;
    }
  }

  /// 获取登录信息
  static Map<String, dynamic> getLoginInfo() {
    return {
      'is_logged_in': getBool('is_logged_in', defValue: false),
      'username': getString('current_username', defValue: ''),
      'user_id': getString('current_user_id', defValue: ''),
      'token': getString('current_token', defValue: ''),
      'remember_password': getBool('remember_password', defValue: false),
      'saved_password': getString('saved_password', defValue: ''),
    };
  }

  /// 清除登录信息
  static Future<bool> clearLoginInfo() async {
    try {
      await remove('is_logged_in');
      await remove('current_username');
      await remove('current_user_id');
      await remove('current_token');
      await remove('remember_password');
      await remove('saved_password');
      await remove('user_info');
      await remove('is_guest_mode');
      return true;
    } catch (e) {
      debugLog('清除登录信息失败: $e');
      return false;
    }
  }

  /// 检查是否已登录
  static bool isLoggedIn() {
    return getBool('is_logged_in', defValue: false) ?? false;
  }

  /// 检查是否为游客模式
  static bool isGuestMode() {
    return getBool('is_guest_mode', defValue: false) ?? false;
  }

  /// 获取当前用户名
  static String getCurrentUsername() {
    return getString('current_username', defValue: '') ?? '';
  }

  /// 获取当前用户ID
  static String getCurrentUserId() {
    return getString('current_user_id', defValue: '') ?? '';
  }

  /// 获取当前令牌
  static String getCurrentToken() {
    return getString('current_token', defValue: '') ?? '';
  }

  /// 保存用户详细信息
  static Future<bool> saveUserInfo(Map<String, dynamic> userInfo) async {
    return await putObject('user_info', userInfo) ?? false;
  }

  /// 获取用户详细信息
  static Map<String, dynamic>? getUserInfo() {
    final result = getObject('user_info');
    if (result is Map<String, dynamic>) {
      return result;
    } else if (result is Map) {
      return Map<String, dynamic>.from(result);
    }
    return null;
  }
}
